<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>心电数据详情</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
</head>

<body class="bg-gray-100 font-sans min-h-screen">
  <div class="p-6 max-w-6xl mx-auto">
    <!-- 顶部栏 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-semibold text-blue-700">📈 设备 {{ device.device_id }} 的心电数据</h1>
      <button id="backBtn" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">返回</button>
    </div>

    <!-- 无数据提示 -->
    <div id="noData" class="hidden text-center text-gray-600 text-lg bg-white py-10 rounded-lg border border-gray-200 shadow-sm">
      🚫 该设备暂未使用
    </div>

    <!-- 分页列表 -->
    <div id="record-list" class="space-y-3 mb-6"></div>

    <div id="pagination" class="flex justify-center items-center gap-4 mt-4 hidden">
      <button id="prevPage" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">上一页</button>
      <span>第 <span id="currentPage">1</span> / <span id="totalPage">1</span> 页</span>
      <button id="nextPage" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">下一页</button>
    </div>

    <!-- 弹窗 -->
    <div id="ecgModal" class="hidden fixed inset-0 bg-black bg-opacity-60 justify-center items-center z-50">
      <div class="bg-white rounded-xl shadow-lg p-5 w-11/12 max-w-6xl relative">
        <h2 id="recordTitle" class="text-lg font-semibold text-center text-blue-600 mb-4">心电波形图</h2>
        <div id="ecgChart" class="w-full h-[480px]"></div>

        <!-- 缩放模式控制 -->
        <div class="flex justify-between items-center mt-4">
          <div class="flex items-center gap-2">
            <label for="zoomMode" class="text-gray-700 font-medium">缩放模式：</label>
            <select id="zoomMode" class="border rounded px-2 py-1 text-sm">
              <option value="xy">双轴缩放</option>
              <option value="x">仅横轴缩放</option>
              <option value="y">仅纵轴缩放</option>
            </select>
          </div>
          <div class="flex gap-3">
            <button id="resetZoom" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">重置缩放</button>
            <button id="closeModal" class="bg-gray-400 text-white px-3 py-1 rounded hover:bg-gray-500">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
  window.addEventListener("DOMContentLoaded", () => {
    const records = JSON.parse(`{{ records | tojson | safe }}`);
    const listContainer = document.getElementById("record-list");
    const modal = document.getElementById("ecgModal");
    const chartDiv = document.getElementById("ecgChart");
    const titleEl = document.getElementById("recordTitle");
    const pagination = document.getElementById("pagination");
    const noDataEl = document.getElementById("noData");
    const zoomModeSelect = document.getElementById("zoomMode");
    const sampleRate = 250;
    let currentPage = 1;
    const pageSize = 10;
    const totalPage = Math.max(1, Math.ceil(records.length / pageSize));
    let currentTrace = null;

    document.getElementById("backBtn").onclick = () => window.history.back();

    if (!records || records.length === 0) {
      noDataEl.classList.remove("hidden");
      pagination.classList.add("hidden");
      return;
    }

    function renderPage(page) {
      listContainer.innerHTML = "";
      const start = (page - 1) * pageSize;
      const end = Math.min(start + pageSize, records.length);

      records.slice(start, end).forEach((rec, i) => {
        const index = start + i;
        const endStr = rec.end_time ? ` ~ ${rec.end_time}` : "";
        const div = document.createElement("div");
        div.className =
          "flex justify-between items-center bg-white border border-gray-300 rounded-lg p-3 hover:bg-blue-50 transition";
        div.innerHTML = `
          <div class='text-blue-700 font-mono text-base'>
            ${rec.start_time}${endStr}
          </div>
          <button class='view-btn bg-green-500 text-white px-4 py-1 rounded hover:bg-green-600' data-index='${index}'>
            查看
          </button>`;
        listContainer.appendChild(div);
      });

      document.getElementById("currentPage").innerText = currentPage;
      document.getElementById("totalPage").innerText = totalPage;
      pagination.classList.remove("hidden");

      document.querySelectorAll(".view-btn").forEach(btn => {
        btn.onclick = e => showRecord(records[parseInt(e.target.dataset.index)]);
      });
    }

    async function showRecord(record) {
      if (!record || !record.data) return alert("该记录没有心电数据");

      const dataArr = record.data.split(",").map(v => parseFloat(v)).filter(v => !isNaN(v));
      const startTime = new Date(record.start_time);
      const timeArr = dataArr.map((_, i) => new Date(startTime.getTime() + (i / sampleRate) * 1000));

      titleEl.textContent = `心电波形图 | ${record.start_time}${record.end_time ? " ~ " + record.end_time : ""}`;
      modal.classList.remove("hidden");
      modal.classList.add("flex");
      await new Promise(r => setTimeout(r, 200));

      const trace = {
        x: timeArr,
        y: dataArr,
        mode: "lines",
        line: { color: "rgb(16,185,129)", width: 1 },
        hoverinfo: "x+y",
        name: "心电信号"
      };

      const layout = {
        margin: { l: 60, r: 30, t: 20, b: 50 },
        xaxis: {
          title: "时间",
          type: "date",
          tickformat: "%H:%M:%S",
          showgrid: true
        },
        yaxis: {
          title: "电压 (mV)",
          range: [-1, 1],
          showgrid: true
        },
        dragmode: "pan",
        plot_bgcolor: "white",
        paper_bgcolor: "white"
      };

      const config = {
        responsive: true,
        scrollZoom: true,
        displaylogo: false,
        displayModeBar: true,
        modeBarButtonsToRemove: ["lasso2d", "select2d"]
      };

      Plotly.newPlot(chartDiv, [trace], layout, config);
      currentTrace = { trace, layout };
    }

    // ✅ 改变缩放模式
    zoomModeSelect.addEventListener("change", e => {
      const mode = e.target.value;
      if (!currentTrace) return;

      let fixedX = false, fixedY = false;
      if (mode === "x") fixedY = true;
      else if (mode === "y") fixedX = true;

      Plotly.relayout(chartDiv, {
        "xaxis.fixedrange": fixedX,
        "yaxis.fixedrange": fixedY
      });
    });

    // ✅ 按钮功能
    document.getElementById("resetZoom").onclick = () => {
      if (!currentTrace) return;
      Plotly.relayout(chartDiv, {
        "xaxis.autorange": true,
        "yaxis.range": [-1, 1]
      });
    };

    document.getElementById("closeModal").onclick = () => modal.classList.add("hidden");
    document.getElementById("prevPage").onclick = () => {
      if (currentPage > 1) { currentPage--; renderPage(currentPage); }
    };
    document.getElementById("nextPage").onclick = () => {
      if (currentPage < totalPage) { currentPage++; renderPage(currentPage); }
    };

    renderPage(currentPage);
  });
  </script>
</body>
</html>
